package com.mxx.v3.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mxx.v3.dao.mapper.TProcedureDayTaskMapper;
import com.mxx.v3.dao.mapper.TProcedureMapper;
import com.mxx.v3.dao.mapper.TWorkpieceMapper;
import com.mxx.v3.dao.mapper.TWorkpieceMouthTaskMapper;
import com.mxx.v3.utils.DateUtils;
import com.mxx.v3.utils.PageQuery;
import com.mxx.v3.dto.ProcedureDto;
import com.mxx.v3.dto.WorkpieceDto;
import com.mxx.v3.pojo.*;
import com.mxx.v3.service.WorkpieceService;
import com.mxx.v3.web.query.WorkpieceQuery;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WorkpieceServiceImpl implements WorkpieceService {

    @Autowired
    private TWorkpieceMapper tWorkpieceMapper;
    @Autowired
    private TProcedureMapper tProcedureMapper;
    @Autowired
    private TProcedureDayTaskMapper tProcedureDayTaskMapper;
    @Autowired
    private TWorkpieceMouthTaskMapper tWorkpieceMouthTaskMapper;


    @Override
    public PageInfo<WorkpieceDto> getWorkpieceList(PageQuery<WorkpieceQuery> workpiecePageQuery) {



        // 设置分页拦截器
        Page<TWorkpiece> tWorkpiecePage = PageHelper.startPage(workpiecePageQuery.getPage(), workpiecePageQuery.getLimit(), true);

        // 条件查询 被分页拦截的表
        TWorkpieceExample tWorkpieceExample = new TWorkpieceExample();
        TWorkpieceExample.Criteria tWorkpieceCriteria = tWorkpieceExample.createCriteria();

        // 条件筛选
        WorkpieceQuery workpieceQuery = workpiecePageQuery.getQueryItem();
        String year_month = workpieceQuery.getMonth();// 2018-05
        Integer planStartDay=Integer.parseInt(workpieceQuery.getDay());  //计划下发的日期

        // ProductCode
        if(!StringUtils.isEmpty(workpieceQuery.getProductCode())){
            tWorkpieceCriteria.andProductCodeEqualTo(workpieceQuery.getProductCode());
        }
        // WorkpieceCode
        if(!StringUtils.isEmpty(workpieceQuery.getWorkpieceCode())){
            tWorkpieceCriteria.andWorkpieceCodeEqualTo(workpieceQuery.getWorkpieceCode());
        }
        // WorkpieceName
        if(!StringUtils.isEmpty(workpieceQuery.getWorkpieceName())){
            tWorkpieceCriteria.andWorkpieceNameLike("%"+workpieceQuery.getWorkpieceName()+"%");
        }

        // 查询，得到一页的list
        List<TWorkpiece> tWorkpieces = tWorkpieceMapper.selectByExample(tWorkpieceExample);

        // 遍历tWorkpieces，封装workpieceDtos
        List<WorkpieceDto> workpieceDtos = new ArrayList<>();
        for (TWorkpiece tWorkpiece : tWorkpieces) {
            WorkpieceDto workpieceDto = new WorkpieceDto();

            workpieceDto.setId(tWorkpiece.getId());
            workpieceDto.setProductCode(tWorkpiece.getProductCode());
            workpieceDto.setWorkpieceCode(tWorkpiece.getWorkpieceCode());
            workpieceDto.setWorkpieceName(tWorkpiece.getWorkpieceName());

            // mouthCount
            TWorkpieceMouthTaskExample tWorkpieceMouthTaskExample = new TWorkpieceMouthTaskExample();
            TWorkpieceMouthTaskExample.Criteria tWorkpieceMouthTaskCriteria = tWorkpieceMouthTaskExample.createCriteria();
            tWorkpieceMouthTaskCriteria.andProductCodeEqualTo(tWorkpiece.getProductCode());
            tWorkpieceMouthTaskCriteria.andWorkpieceCodeEqualTo(tWorkpiece.getWorkpieceCode());
            tWorkpieceMouthTaskCriteria.andMouthDateEqualTo(year_month);
            List<TWorkpieceMouthTask> tWorkpieceMouthTasks = tWorkpieceMouthTaskMapper.selectByExample(tWorkpieceMouthTaskExample);
            if(tWorkpieceMouthTasks!=null
                    && tWorkpieceMouthTasks.size()>0
                    && tWorkpieceMouthTasks.get(0)!=null){
                TWorkpieceMouthTask tWorkpieceMouthTask = tWorkpieceMouthTasks.get(0);
                workpieceDto.setMouthPlanCount(tWorkpieceMouthTask.getMouthAmount());
            }


            // procedureList
            // 查询该workpiece下所有的procedure
            TProcedureExample tProcedureExample = new TProcedureExample();
            TProcedureExample.Criteria tProcedureCriteria = tProcedureExample.createCriteria();
            tProcedureCriteria.andProductCodeEqualTo(tWorkpiece.getProductCode());
            tProcedureCriteria.andWorkpieceCodeEqualTo(tWorkpiece.getWorkpieceCode());
            tProcedureExample.setOrderByClause("procedure_code");
            List<TProcedure> tProcedures = tProcedureMapper.selectByExample(tProcedureExample);

            // 遍历tProcedures，封装procedureMap
//            Map<Integer, ProcedureDto> procedureMap = workpieceDto.getProcedureMap();
            List<ProcedureDto> procedureDtoList = new ArrayList<>();
           // procedureDtoList.add(needPlan());
            for (TProcedure tProcedure : tProcedures) {
                /*ProcedureDto procedureDto = procedureMap
                        .get(tProcedure.getProcedureCode());*/

                ProcedureDto procedureDto = new ProcedureDto();

                /////下面是模拟的数据////
                procedureDto.setMasterLessThanPassive(0);
                procedureDto.setMouthPlanCount(0);

                procedureDto.setMouthStartVlaue(0);

                //数据模拟结束

                procedureDto.setProcedureName(tProcedure.getProcedureName());

                // 查询tProcedure的一个月的t_task
                TProcedureDayTaskExample
                        tProcedureDayTaskExample = new TProcedureDayTaskExample();
                TProcedureDayTaskExample.Criteria tTaskCriteria = tProcedureDayTaskExample.createCriteria();
                tTaskCriteria.andProductCodeEqualTo(tProcedure.getProductCode());
                tTaskCriteria.andWorkpieceCodeEqualTo(tProcedure.getWorkpieceCode());
                tTaskCriteria.andProcedureCodeEqualTo(tProcedure.getProcedureCode());
                // saveTime
                //遍历当月的所有计划数量
                int yearNum = Integer.parseInt(year_month.split("-")[0]);
                int mouthNum = Integer.parseInt(year_month.split("-")[1]);
                Date monthStart;
                if(mouthNum!=1)
                monthStart = DateUtils.getOneDayStart(yearNum, mouthNum-1,planStartDay);
                else
                monthStart = DateUtils.getOneDayStart(yearNum-1, 12,planStartDay);
                Date monthEnd = DateUtils.getOneDayEnd(yearNum,mouthNum,planStartDay-1);
                tTaskCriteria.andSaveTimeBetween(monthStart, monthEnd);
                List<TProcedureDayTask> tProcedureDayTasks = tProcedureDayTaskMapper.selectByExample(tProcedureDayTaskExample);
                Integer days=0;  //计算从上个月28号到这个月的28号之前共多少天,如果是一月，就从上一年的12月开始算
                if(mouthNum==1)
                {
                    days=DateUtils.getMouthDay(DateUtils.getMonthEnd(yearNum, mouthNum-1));
                }
                else
                {
                    days=DateUtils.getMouthDay(DateUtils.getMonthEnd(yearNum-1, 12));
                }
                  Integer[] mouthCountArray = new Integer[days];
                // 总月实际完成数
                int mouthActualCount=0;
                for (TProcedureDayTask tProcedureDayTask : tProcedureDayTasks) {

                    // key 2019-09-09   value 40
                    String mouthDay = new SimpleDateFormat("yyyy-MM-dd")
                            .format(tProcedureDayTask.getSaveTime())
                            .split("-")[2];

                    // 13号 下标12
                    mouthCountArray[Integer.parseInt(mouthDay)-1] = tProcedureDayTask.getDayAmount();
                    mouthActualCount+=tProcedureDayTask.getDayAmount();
                }
                procedureDto.setMouthCountArray(mouthCountArray);
                procedureDto.setProcedureCode(tProcedure.getProcedureCode());
                procedureDto.setMouthActualCount(mouthActualCount);
                ///20191105  计算累计完成数
                procedureDto.setMouthTotal(procedureDto.getMouthStartVlaue()+procedureDto.getMouthActualCount());
                //月计划数： 改为  月下达计划数  = 每日完成数合计
                procedureDto.setMouthPlanCount(procedureDto.getMouthTotal());
                //累计差数
                procedureDto.setLessThanCount(procedureDto.getMouthPlanCount()-procedureDto.getMouthTotal());
                procedureDtoList.add(procedureDto);
            }

            workpieceDto.setProcedureList(procedureDtoList);

            // add
            workpieceDtos.add(workpieceDto);
        }
        //移除计划数量为0的产品
        Iterator<WorkpieceDto> iterator = workpieceDtos.iterator();
        while (iterator.hasNext()){
            WorkpieceDto workpieceDto = iterator.next();
            if (workpieceDto.getMouthPlanCount() == null || workpieceDto.getMouthPlanCount() == 0){
                iterator.remove();
            }
        }

        // 封装pageInfo

        PageInfo<WorkpieceDto> pageInfo = new PageInfo<>(workpieceDtos);
        pageInfo.setTotal(tWorkpiecePage.getTotal());

        return pageInfo;
    }
    //需求计划列
    public ProcedureDto needPlan()
    {
        ProcedureDto procedureDto = new ProcedureDto();
        /////下面是模拟的数据////
        procedureDto.setMasterLessThanPassive(0);
        procedureDto.setMouthPlanCount(0);

        procedureDto.setMouthStartVlaue(0);



        procedureDto.setProcedureName("需求计划");
        Integer[] mouthCountArray = new Integer[31];
        for (int i=0;i<31;i++) {
            mouthCountArray[i] = 0;
        }
        procedureDto.setMouthTotal(0);
        //数据模拟结束
        procedureDto.setMouthCountArray(mouthCountArray);
        return procedureDto;
    }

}
